from flask import Flask, render_template, request,send_from_directory
import os
from werkzeug.utils import secure_filename
from pathlib import Path

app = Flask(__name__)
app.config['UPLOAD_FOLDER']='upload/'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload')
def upload_file():
    return render_template('upload.html')

@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
    if request.method == 'POST':
        files = request.files.getlist('files')
        for file in files:
            # filename=secure_filename(file.filename) # 会滤掉中文字符
            filename=file.filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print(f'file {filename} uploaded successfully')
        return render_template('upload.html')
    else:
        return render_template('upload.html')

@app.route('/see_uploaded_files')
def see_uploaded_files():
    filenames=[]
    for entry in Path(app.config['UPLOAD_FOLDER']).iterdir():
        filenames.append(entry.name)
    return render_template('see_uploaded_files.html',filenames=filenames)

@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

@app.route('/tell', methods=['POST'])
def tell():
    print(request.form['words'])
    return render_template('index.html')

@app.route('/test',methods=['GET','POST'])
def test():
    if request.method=='POST':
        info=request.form.to_dict()
        print(info.get('metrics','123'))
        print(type(info.get('a')),info.get('a'))
        return render_template('test.html',content=info.get('metrics','123'))
    return render_template('test.html',content='')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True,port=5006)
